# -*- coding: utf-8 -*-
import io
import json
import os
import traceback

import yaml

from fastrunner import models
from fastrunner.utils.parser import Format


def load_yaml_file(yaml_file):
    """ load yaml file and check file content format
    """
    with io.open(yaml_file, 'r', encoding='utf-8') as stream:
        try:
            yaml_content = yaml.load(stream)
        except:
            raise ValueError(traceback.print_exc())

        return yaml_content


def load_json_file(json_file):
    """ load json file and check file content format
    """
    with io.open(json_file, encoding='utf-8') as data_file:
        try:
            json_content = json.load(data_file)
        except:
            raise ValueError(traceback.print_exc())
        return json_content


def get_desc(content):
    desc_dict = {}
    if isinstance(content, dict):
        for key in content.keys():
            desc_dict[key] = ""
    elif isinstance(content, list):
        for key_value in content:
            for key in key_value.keys():
                desc_dict[key] = ""
    return desc_dict


def trans_req_data_to_variables(req_value):
    req_dict = {}
    variable_dict_list = []

    if isinstance(req_value, str):
        params_list = req_value.split('&')
        for key_value in params_list:
            if "=" in key_value:
                data_key, data_value = key_value.split('=')
                req_dict[data_key] = "$" + str(data_value)
                variable_dict_list.append({data_key: data_value})

    elif isinstance(req_value, dict):
        for key in req_value.keys():
            req_dict[key] = "$" + str(key)
            variable_dict_list.append({key: req_value.get(key, '')})

    elif isinstance(req_value, list):
        for key_value in req_value:
            for key in key_value.keys():
                req_dict[key] = "$" + str(key)
                variable_dict_list.append({key: key_value.get(key, '')})
    return req_dict, variable_dict_list


def paeser_api(content):
    """"生成前端的标准格式
        暂未对file做处理
    """
    request_data_list=[]
    test_list=[]
    if isinstance(content, dict):
        """ v2 httprunner """
        print("content is dict:",content)
        pass
    elif isinstance(content, list):
        """httprunner v1"""
        test_list = [test["test"] for test in content if "test" in test]
        # content = content[0]["test"]
    else:
        return ''
    for test in test_list:
        request_data = {
            "header": {
                "header": {},
                "desc": {}
            },
            "request": {
                "form": {
                    "data": {},
                    "desc": {}
                },
                "json": {},
                "params": {
                    "params": {},
                    "desc": {}
                },
                "files": {
                    "files": {},
                    "desc": {}
                }
            },
            "extract": {
                "extract": [],
                "desc": {}
            },
            "validate": {
                "validate": []
            },
            "variables": {
                "variables": [],
                "desc": {}
            },
            "hooks": {
                "setup_hooks": [],
                "teardown_hooks": []
            },
            "url": "",
            "method": "",
            "name": "",
            "times": 1
        }
        for key, value in test.items():
            if key == 'name':
                request_data["name"] = value
            if key == 'def':
                request_data["name"] = value.split('(')[0]
            if key == 'request':
                for req_key, req_value in value.items():
                    if req_key == 'data':
                        request_data["request"]["form"]["data"] = trans_req_data_to_variables(req_value)[0]
                        request_data["request"]["form"]["desc"] = get_desc(req_value)
                        request_data["variables"]["variables"] = trans_req_data_to_variables(req_value)[1]
                        request_data["variables"]["desc"] = get_desc(req_value)
                    if req_key == 'headers':
                        request_data["header"]["header"] = req_value
                        request_data["header"]["desc"] = get_desc(req_value)
                    if req_key == 'json':
                        request_data["request"]["json"] = req_value
                    if req_key == 'params':
                        request_data["request"]["params"]["params"] = req_value
                        request_data["request"]["params"]["desc"] = get_desc(req_value)
                    if req_key == 'method':
                        request_data["method"] = req_value
                    if req_key == 'url':
                        request_data["url"] = req_value
            if key == 'extract' and value:
                request_data["extract"]["extract"] = value
                request_data["extract"]["desc"] = get_desc(value)
            if key == 'validate':
                request_data["validate"]["validate"] = value
            if key == 'variables':
                if isinstance(value, list):
                    request_data["variables"]["variables"] = value
                if isinstance(value, dict):
                    for var_key, var_value in value.items():
                        request_data["variables"]["variables"].append({var_key: var_value})
                request_data["variables"]["desc"] = get_desc(value)
            if key == 'setup_hooks':
                request_data["hooks"]["setup_hooks"] = value
            if key == 'teardown_hooks':
                request_data["hooks"]["teardown_hooks"] = value
            if key == 'times':
                request_data["times"] = value
        request_data_list.append(request_data)
    return request_data_list


def save_api(request_data, project_id, relation_id):
    if request_data:
        api = Format(request_data)
        api.parse()
        api_body = {
            'name': api.name,
            'body': api.testcase,
            'url': api.url,
            'method': api.method,
            'project_id': project_id,
            'relation': relation_id
        }
        try:
            models.API.objects.create(**api_body)
        except:
            print(traceback.print_exc())


# 递归处理
def import_api_data(har2case_file, project_id, relation_id):
    """
    file_path: import api.json,use har2case to generate by har file
    """

    if os.path.isfile(har2case_file):
        file_suffix = os.path.splitext(har2case_file)[1].lower()
        file_content={}
        if file_suffix == '.json':
            file_content = load_json_file(har2case_file)
        elif file_suffix in ['.yaml', '.yml']:
            file_content = load_yaml_file(har2case_file)
        request_data_list = paeser_api(file_content)
        for request_data in request_data_list:
            save_api(request_data, project_id, relation_id)


if __name__ == '__main__':
    MY_API_FILEPATH = r'E:\api\b.json'
    PROJECT_ID = 18  # 看自己现在的项目id
    RELATION_ID = 1  # 看自己现在的节点id
    import_api_data(MY_API_FILEPATH, PROJECT_ID, RELATION_ID)
